package com.cn.icss.service.impl;

import com.cn.icss.service.IThumbUpService;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

/**
 * @中软华腾软件系统有限公司,未经授权不得擅自传播
 * @类描述:
 * @类名称:ThumbUpServiceImpl
 * @作者: Administrator
 * @编辑时间: 2020/05/12 10:07
 * @版本: 1.0
 */
public class ThumbUpServiceImpl implements IThumbUpService {
    public static final String THUMBUP="thumbup";
    // 引入Redis
    Cache userCache = Redis.use("liveStream");

    @Override
    public Object queryThumbUp(String key) {
        Object result = this.userCache.get(key+"-"+ THUMBUP);
        if(result==null){
            result = 0;
        }
        return result;
    }

    @Override
    public void thumbUpPlus(String key) {
        try{
            increaseNum(key, 1);
        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException("点赞入库Redis异常!");
        }
    }

    @Override
    public void thumbUpMinus(String key) {
        try{
            if(Long.parseLong(userCache.get(key+"-"+ THUMBUP))>0){
                increaseNum(key, -1);
            }else{
                userCache.set(key+"-"+THUMBUP,0);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw  new RuntimeException("取消点赞入库Redis异常!");
        }
    }

    @Override
    public void clearThumbUp(String key) {
        try{
            userCache.del(key+"-"+THUMBUP);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("删除key失败!");
        }
    }


    private void increaseNum(String key, long num){
        userCache.incrBy(key+"-"+THUMBUP, num);
    }

}
